/*
Copyright 2010-2011 CumulusCloud
http://cumuluscloud.cc

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package appmanager.server.tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Logger;

public class HashUtilities {
	private static Logger logger = java.util.logging.Logger.getLogger(HashUtilities.class.getName());

	public static String hash(File file) {
		MessageDigest digest = null;
		try {
			digest = MessageDigest.getInstance("SHA-512");
		} catch (NoSuchAlgorithmException e) {
			logger.severe("The SHA-512 algorithm was not found");
			e.printStackTrace();
			return null;
		}
		digest.reset();
		
		FileInputStream input = null;
		try {
			input = new FileInputStream(file);
			
			byte[] b = new byte[1024];
			int len;
			while ( (len = input.read(b)) != -1) {
				digest.update(b, 0, len);
			}
			
			input.close();
		} catch (FileNotFoundException e) {
			logger.severe("File not found");
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			logger.severe("Problem reading file");
			e.printStackTrace();
			return null;
		}

		return bytesToHex(digest.digest());
	}
	
	public static String hash(String text) {
		MessageDigest digest = null;
		try {
			digest = MessageDigest.getInstance("SHA-512");
		} catch (NoSuchAlgorithmException e) {
			logger.severe("The SHA-512 algorithm was not found");
			e.printStackTrace();
			return null;
		}
		digest.reset();
		digest.update(text.getBytes());
		return bytesToHex(digest.digest());
	}

	private static String bytesToHex(byte[] bytes) {
		String result = "";

		for (byte next : bytes) {
			String part = Integer.toHexString(0xFF & next);
			
			if (part.length() == 1) part = "0" + part;
			
			result += part;
		}

		return result;
	}
}
